package oa.hleast.common.upload.component;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import oa.hleast.common.upload.config.UploadProperties;
import io.minio.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Locale;

@Slf4j
@ConditionalOnProperty(prefix = "upload",value = {"provider"},havingValue = "min-io")
@EnableConfigurationProperties({UploadProperties.class})

public class MinIOService implements InitializingBean, IFileService {

    private UploadProperties uploadProperties;

    public MinIOService(UploadProperties UploadProperties) {
        this.uploadProperties = UploadProperties;
    }

    private MinioClient client;

    @Override
    public void afterPropertiesSet() {
        Assert.notBlank(uploadProperties.getEndpoint(), "URL 为空");
        Assert.notBlank(uploadProperties.getAccessKey(), "accessKey为空");
        Assert.notBlank(uploadProperties.getSecretKey(), "secretKey为空");
        this.client = new MinioClient.Builder()
                .endpoint(uploadProperties.getEndpoint())
                .credentials(uploadProperties.getAccessKey(), uploadProperties.getSecretKey())
                .build();
    }

    @SneakyThrows
    public void createBucketIfAbsent(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                .bucket(bucketName)
                .build();
        if (!client.bucketExists(bucketExistsArgs)) {
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                    .bucket(bucketName).build();
            client.makeBucket(makeBucketArgs);
        }
    }

    public String uploadFile(InputStream file, String ext, String bucketName) throws Exception {
        String objectName = IdUtil.simpleUUID() + "." + ext;
        return putObject(bucketName, objectName, file);
    }

    /**
     * 获取图片分辨率并添加到文件名的后面如123.jpg --> 123_480x480.jpg
     * @param objectName
     * @param inputStream
     * @return
     */
    private String getImageResolution(String objectName, InputStream inputStream) {
        String suffix =  objectName.substring(objectName.lastIndexOf(".")+1).toLowerCase();
        if (!"jpg|png|bmp".contains(suffix)) {
            return objectName;
        }

        String imageResolutionName = objectName;
        try {
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            String[] objectNames = objectName.split("\\.");
            imageResolutionName = objectNames[0] + "_"+ bufferedImage.getWidth() + "x" + bufferedImage.getHeight() + "." + objectNames[1];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return imageResolutionName;
    }

    @Override
    public String putObject(String bucketName, String objectName, InputStream inputStream) throws Exception {

        String objectNameWithResolution = getImageResolution(objectName, inputStream);
        createBucketIfAbsent(bucketName);
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectNameWithResolution)
                .contentType("*/*")
                .stream(inputStream, inputStream.available(), -1)
                .build();
        client.putObject(putObjectArgs);
        String path = client.getObjectUrl(bucketName, objectNameWithResolution);
        return path.replace(uploadProperties.getEndpoint(), uploadProperties.getShareUrl());
    }

    @Override
    public void removeObject(String bucketName, String objectName) throws Exception {
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        client.removeObject(removeObjectArgs);
    }

    public static void main(String[] args) {
        String objectName = "411431ecd0134ece93baff6b2f1e4458.png";
        String suffix =  objectName.substring(objectName.lastIndexOf(".")+1).toLowerCase();
        System.out.println(!"jpg|png|bmp".contains(suffix));
        String[] objectNames = objectName.split("\\.");
        System.out.println(objectNames.length);
    }
}
